package net.sshiffon;

import org.apache.log4j.Logger;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

public class SshiffonConnector {

    private static Logger logger = Logger.getLogger(SshiffonConnector.class);
    public static final String KNOWN_HOSTS = System.getProperty("user.home") + "/.sshiffon/known_hosts";
    private String user;
    private String host;
    private int port = 22;
	private boolean isKeepAlive;
	private Integer keepAliveSeconds;
	private Integer connectionTimeout;
    
    public SshiffonConnector(String user, String host, int port, boolean isKeepAlive, Integer keepAliveSeconds, Integer connectionTimeout)
    {
    	this.user= user;
    	this.host= host;
    	this.port = port;
    	this.isKeepAlive= isKeepAlive;
    	this.keepAliveSeconds= keepAliveSeconds;
    	this.connectionTimeout= connectionTimeout;
    }
    
	public Session connectSession(UserInfo userInfo) throws JSchException {
        logger.info("Connecting new JSch Session "+this.user+"@"+this.host+":"+this.port);

		JSch jsch  = new JSch();
		Session _session = null;
                jsch.setKnownHosts(KNOWN_HOSTS);

		_session = jsch.getSession(user, host, port);
		_session.setUserInfo(userInfo);

		final java.util.Properties config = new java.util.Properties();
		config.put("compression.s2c", "zlib,none");
		config.put("compression.c2s", "zlib,none");
		_session.setConfig(config);
		if(!isKeepAlive)
		{
			_session.setServerAliveCountMax(0);
		}
		_session.setServerAliveInterval(this.keepAliveSeconds);
		_session.setTimeout(connectionTimeout);
//    	String xhost="127.0.0.1";
//	    int xport=0;
//	    _session.setX11Host(xhost);
//	    _session.setX11Port(xport+6000);
		
		logger.info("Connecting session now");
		_session.connect();
		_session.setTimeout(0);
		logger.debug("Connected ... save known host keys ");
        KeyManager.saveKeys(jsch, KNOWN_HOSTS);

        if(isKeepAlive)
        {
        	Thread x = new Thread(new KeepaliveManager(_session, this.keepAliveSeconds));
        	x.start();
        }
		return _session;
	}
}
